<?php

namespace App\Http\Controllers\System;


use App\Http\Controllers\Controller;
use App\Repositories\Contracts\UserRepositoryInterface;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;

class UserController extends Controller {
  //

  /**
   * @var UserRepositoryInterface serRepositoryInterface
   */
  private $userRepository;

  /**
   * UserController constructor.
   *
   * @param UserRepositoryInterface $userRepository
   */
  public function __construct( UserRepositoryInterface $userRepository ) {
    $this->userRepository = $userRepository;
  }

  public function lists() {
    $result = $this->userRepository->paginate();

    return $this->result( true, $result );
  }

  public function remove( $id = 0 ) {

    return $this->result( $this->userRepository->delete( $id ) );
  }

  /**
   * 管理员，对用户进行修改，新增操作
   *
   * @param Request $request
   *
   * @return \Illuminate\Http\JsonResponse
   */
  public function save( Request $request ) {
    $id   = intval( $request->input( "id", 0 ) );
    $data = $request->only( 'name', 'email', 'password' );
    $this->userValidation( $data, $id )->validate();
    if ( $id > 0 ) {
      $data = $this->userRepository->updateRich( $data, $id );
    } else {
      $data = $this->userRepository->create( $data );
    }

    return $this->result( $data != null, $data );
  }


  /**
   * 对用户新建、修改的验证
   * @param array $data
   *
   * @return \Illuminate\Contracts\Validation\Validator
   */
  public function userValidation( array $data,$id ) {

    $roles = [
      'name'     => [ 'required', 'string', 'max:255' ],
      'email'    => [ 'required', 'string', 'email', 'max:255' ],
      'password' => 'required|string|min:6'
    ];

    if ( $id < 1 ) {
      // 新用户做唯一性检测
      $roles['name'][]  = "unique:users,name";
      $roles['email'][] = "unique:users,email";
    } else {
      // 老用户不能与其它人同名
      $roles['name'][]  = Rule::unique( 'users' )->ignore( $id );
      $roles['email'][] = Rule::unique( 'users' )->ignore( $id );
      // 没有设置密码时忽略
      if ( ! $data['password'] ) {
        unset( $roles['password'] );
      }
    }

    return Validator::make( $data, $roles );

  }
}
